<template>
  <div class="app-container">
    <el-input
      v-model="search.keyword"
      placeholder="keywords"
      style="width:300px"
    />
    <el-date-picker
      v-model="search.startDate"
      type="date"
      placeholder="Start Date"
      value-format=" yyyy-MM-dd"
      format="yyyy-MM-dd"
      clearable
    />
    <el-date-picker
      v-model="search.endDate"
      type="date"
      placeholder="End Date"
      value-format="yyyy-MM-dd"
      format="yyyy-MM-dd"
      clearable
    />
    <el-button type="primary" @click="getList">Search</el-button>
    <el-input v-model.number="total_row_num" placeholder="Quantity" style="width: 100px" @oninput="value=value.replace(/^\d+$|^\d+[.]?\d+$/,'')" />
    <el-button type="primary" icon="el-icon-download" circle @click="selectPage" />

    <el-dialog
      :visible.sync="dialogVisible_per"
      title="Download"
      width="500px"
    >
      <div>
        <el-row style="margin-bottom:20px;margin-top: -10px;padding-left: 20px">
          <el-col v-for="item in total_row_total" :key="item" :span="6" style="margin-bottom:10px">
            <el-link type="primary" @click="downloadWorkOrder(item)">Page {{ item }}</el-link>
          </el-col>
        </el-row>
      </div>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible_per = false">Cancel</el-button>
      </div>
    </el-dialog>

    <el-table
      :data="attenceList"
      style="width: 100%;margin-top:30px;"
      border
      :empty-text="empty_text"
      :cell-style="cellChangeColor"
    >
      <el-table-column align="header-center" label="Name" width="100">
        <template slot-scope="scope">{{ scope.row.user_login }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Place" width="100">
        <template slot-scope="scope">
          {{ scope.row.location }}
        </template>
      </el-table-column>

      <el-table-column align="header-center" label="Check-in">
        <template slot-scope="scope">
          <div v-html="scope.row.check_in_time_format"><br>
          </div>
          <div v-html="scope.row.check_in_address"><br>
          </div>
          <div v-html="scope.row.check_in_notes"><br>
          </div>
          <div v-html="scope.row.check_in_temperature" />
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="Check-out">
        <template slot-scope="scope">
          <div v-html="scope.row.check_out_time_format"><br>
          </div>
          <div v-html="scope.row.check_out_address"><br>
          </div>
          <div v-html="scope.row.check_out_notes"><br>
          </div>
          <div v-html="scope.row.check_out_temperature" />
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
      style="margin-top:10px;float:right"
      background
      layout="slot,prev,pager,next"
      :total="totalpage"
      :current-page="search.page"
      :page-size="search.per_page"
      @current-change="handleIndexChange"
    >
      <span class="el-pagination__total">Total {{ totalpage }}</span>
    </el-pagination>

  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { getAttence } from '@/api/attence'
import { getToken } from '@/utils/auth' // get token from cookie

export default {
  data() {
    return {
      empty_text: '',
      search: {
        keyword: '',
        startDate: '',
        endDate: '',
        page: 1,
        request_type: '',
        per_page: 10
      },

      tokenData: '',

      total_row_num: 50,
      total_row_total: undefined,
      dialogVisible_per: false,

      totalpage: 0,
      total: 10,
      pagesize: 1,
      attenceList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false
    }
  },
  computed: {},
  created() {
    // Mock: get all routes and roles list from server
    this.getList()
    this.conToken()
  },
  methods: {
    handleIndexChange(index) {
      this.search.page = index
      this.getPageList(this.search.page)
    },
    async conToken() {
      this.tokenData = getToken()
    },
    async getList() {
      this.empty_text = 'Loading ......'
      await getAttence(this.search)
        .then(res => {
          res.data.forEach(element => {
            if (element.check_out_location) {
              element.location = element.check_in_location + '-' + element.check_out_location
            } else {
              element.location = element.check_in_location
            }

            // check_in
            if (element.check_in_temperature > 37.5) {
              element.check_in_temperature = "<span style='color: red'>" + element.check_in_temperature + '</span>'
            }
            if (element.check_in_time) {
              element.check_in_time = parseTime(element.check_in_time, '{y}-{m}-{d}')
            }

            // check_out
            if (element.check_out_temperature > 37.5) {
              element.check_out_temperature = "<span style='color: red'>" + element.check_out_temperature + '</span>'
            }
            if (element.check_out_time) {
              element.check_out_time = parseTime(element.check_out_time, '{y}-{m}-{d}')
            }
          })

          this.totalpage = res.total
          this.per_page = res.per_page
          this.current_page = res.current_page
          this.attenceList = res.data
          this.empty_text = "Can't find record in table"
        })
        .catch(() => {
          this.attenceList = []
          this.empty_text = "Can't find record in table"
        })
    },
    async downloadWorkOrder(value) {
      this.downloadSearch = Object.assign({}, this.search)
      this.downloadSearch.download = 1
      if (this.downloadSearch.time_start) {
        this.downloadSearch.time_start = parseTime(this.downloadSearch.time_start, '{y}-{m}-{d}')
      }
      if (this.downloadSearch.time_end) {
        this.downloadSearch.time_end = parseTime(this.downloadSearch.time_end, '{y}-{m}-{d}')
      }
      const url = 'user/attence/index?keyword=' + this.downloadSearch.keyword + '&page=' + value + '&per_page=' + this.total_row_num +
      '&time_start=' + this.downloadSearch.startDate + '&time_end=' + this.downloadSearch.endDate + '&request_type=download&token=' + this.tokenData

      window.open(process.env.VUE_APP_BASE_API + url)
    },
    async getPageList(value) {
      this.search.page = value
      this.empty_text = 'Loading ......'
      await getAttence(this.search)
        .then(res => {
          res.data.forEach(element => {
            if (element.check_out_location) {
              element.location = element.check_in_location + '-' + element.check_out_location
            } else {
              element.location = element.check_in_location
            }

            // check_in
            if (element.check_in_temperature > 37.5) {
              element.check_in_temperature = "<span style='color: red'>" + element.check_in_temperature + '</span>'
            }
            if (element.check_in_time) {
              element.check_in_time = parseTime(element.check_in_time, '{y}-{m}-{d}')
            }

            // check_out
            if (element.check_out_temperature > 37.5) {
              element.check_out_temperature = "<span style='color: red'>" + element.check_out_temperature + '</span>'
            }
            if (element.check_out_time) {
              element.check_out_time = parseTime(element.check_out_time, '{y}-{m}-{d}')
            }
          })

          this.total = res.total
          this.totalpage = res.total
          this.currentpage = res.current_page
          this.pagesize = res.per_page
          this.attenceList = res.data
          this.empty_text = "Can't find record in table"
        })
        .catch(() => {
          this.attenceList = []
          this.empty_text = "Can't find record in table"
        })
    },
    async selectPage() {
      if (!this.total_row_num || this.total_row_num <= 0) {
        this.$message({
          type: 'warning',
          message: 'Please enter the quantity per page!'
        })
        return
      } else {
        const per_search = Object.assign({}, this.search)
        per_search.request_type = 'download_query'

        await getAttence(per_search).then(async response => {
          if (response.total > 0) {
            if (response.total <= this.total_row_num) {
              // 直接下载
              return this.downloadWorkOrder(1)
            }
            this.total_row_total = Math.ceil(response.total / this.total_row_num)
            this.dialogVisible_per = true
          } else {
            this.$message({
              type: 'warning',
              message: 'Can\'t find record to download!'
            })
          }
        })
      }
    },
    cellChangeColor({ row, column, rowIndex, columnIndex }) {
      // if (columnIndex == 2) {
      //   if (row.check_in_temperature > 37.5) {
      //     return {color: 'red'}
      //   }
      // }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
